#!/bin/bash -e
# Script for recreating Django DB. Useful when you need to quickly purge and recreate database. 
# Automatically creates Django admin superuser.
# Place script in your project directory and set variables below.
# Call the script like this: ./recreate_db.sh

# These variables need to be set manually
MYSQL_DJANGO_DB="brp"
DJANGO_ADMIN_USER="admin"
DJANGO_ADMIN_PWD="admin"
MYSQL_DJANGO_USER="root"
MYSQL_DJANGO_PWD="blah"

# Do not change anything from this line below
PROJECT_PATH=`pwd`
PROJECT_DIR=`basename \`pwd\``
TRUNK_PATH=`pwd`/..
SQLITE_DB=$PROJECT_DIR.db

# Set env variables
export DJANGO_SETTINGS_MODULE=$PROJECT_DIR.settings
export PYTHONPATH=$PROJECT_PATH:$TRUNK_PATH

# Determine db engine
ENGINE=`python -c "from settings import DATABASES; print DATABASES['default']['ENGINE'].split('.')[-1]"`
echo "DB engine is $ENGINE."

# Recreate database
if [ "$ENGINE" = "sqlite3" ]; then
    echo "Removing $SQLITE_DB ..."
    rm -f $PROJECT_PATH"/"$SQLITE_DB
elif [ "$ENGINE" = "mysql" ]; then
    echo "Droping database $MYSQL_DJANGO_DB ..."
    echo "DROP DATABASE IF EXISTS $MYSQL_DJANGO_DB;" | mysql -u$MYSQL_DJANGO_USER -p$MYSQL_DJANGO_PWD
    echo "Recreating database $MYSQL_DJANGO_DB ..."
    echo "CREATE DATABASE $MYSQL_DJANGO_DB CHARACTER SET utf8 COLLATE utf8_general_ci;" | mysql -u$MYSQL_DJANGO_USER -p$MYSQL_DJANGO_PWD
else
    echo "Database engines supported: sqlite3, mysql. Recreating database failed."
    exit
fi

# Run syncdb
echo "Running syncdb ... "
python2.6 $PROJECT_PATH/manage.py syncdb --noinput

# Create admin superuser
echo "Creating admin superuser ..."
python2.6 -c "from django.contrib.auth.models import User; User.objects.create_superuser('$DJANGO_ADMIN_USER', 'email@email.com', '$DJANGO_ADMIN_PWD')"

# Apply South migrations
echo "Applying South migrations ..."
python2.6 $PROJECT_PATH/manage.py migrate
